package com.example.xmldemo;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class XMLUtil {

    public  static List<PersonModel> parasePerson(InputStream inputStream) throws XmlPullParserException, IOException {
        List<PersonModel> list=null;
        PersonModel personModel = null;
        XmlPullParser pullParser= XmlPullParserFactory.newInstance().newPullParser();
        pullParser.setInput(inputStream,"UTF-8");
        //首次获取时eventType始终为
        int eventType=pullParser.getEventType();
        while (eventType!=XmlPullParser.END_DOCUMENT){
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
                    list=new ArrayList<>();
                    break;
                    case XmlPullParser.START_TAG:
                        switch (pullParser.getName()){
                            case "person":
                                personModel=new PersonModel();
                                personModel.setId(pullParser.getAttributeValue("","id"));
                                break;
                            case "name":
                                if(null!=personModel){
                                    personModel.setName(pullParser.nextText());
                                }
                                break;
                            case "age":
                                if(null!=personModel){
                                    personModel.setAge(pullParser.nextText());
                                }
                                break;
                        }
                        break;
                case XmlPullParser.END_TAG:
                    if("person".equals(pullParser.getName())){
                        list.add(personModel);
                        personModel=null;
                    }
                    break;
            }
            //轮动解析，如果while循环最后没有修改eventype,则会死循环
            eventType=pullParser.next();
        }
        return list;
    }
}
